import { SimplePlayer, Events } from "xgplayer";
import Error from "xgplayer/es/plugins/error";
import Fullscreen from "xgplayer/es/plugins/fullscreen";
import Volume from "xgplayer/es/plugins/volume";
import Time from "xgplayer/es/plugins/time";

import "xgplayer/dist/index.min.css";

import FlvPlugin from "xgplayer-flv";
import { isRef } from "vue";

const useFlv = ({ videoRef, cameraUrl, options = {} }) => {
  const { VITE_API_URL } = import.meta.env;
  let player = null;

  function getFlv() {
    const videoPath = isRef(cameraUrl)
      ? `${VITE_API_URL}/digitaltwins/api/v1/camera/get?rtspUrl=${cameraUrl.value}`
      : `${VITE_API_URL}/digitaltwins/api/v1/camera/get?rtspUrl=${cameraUrl}`;
    // const rstUrl = encodeURI("D:\\download\\0730.mp4");
    // const videoPath = `http://10.1.2.174:8082/api/v1/camera/get?rtspUrl=${rstUrl}`;

    if (!videoRef?.value) {
      setTimeout(() => {
        getFlv();
      }, 1000);
      return;
    }
    let playerOptions = Object.assign(
      {
        el: videoRef.value,
        isLive: true,
        plugins: [FlvPlugin, Error, Fullscreen, Volume, Time],
        autoplay: true,
        width: "100%",
        keyboard: false,
        autoplayMuted: false,
        closeVideoClick: true,
        closeVideoDblclick: true,
        controls: {
          autoHide: false
        },
        flv: {
          bufferBehind: 10,
          maxJumpDistance: 3,
          retryCount: 3,
          retryDelay: 1000,
          loadTimeout: 10000,
          maxReaderInterval: 5000,
          analyzeDuration: 10000,
          enableContextmenu: false,
          maxLatency: 10,
          targetLatency: 5,
          disconnectTime: 10,
          fetchOptions: {
            // 该参数会透传给 fetch，默认值为 undefined
            mode: "cors"
          }
        },
        url: videoPath
      },
      options
    );
    player = new SimplePlayer(playerOptions);
    player.on(Events.ERROR, error => {
      console.error("摄像头报错--->", error); // xgplayer 中的 Errors 对象
    });
  }
  const reloadVideo = () => {
    destoryVideo();
    getFlv();
  };
  const destoryVideo = () => {
    player?.destroy(); // 销毁播放器
    player = null; // 将实例引用置空
  };
  // let timer = null;
  const videoClick = () => {};
  return {
    getFlv,
    videoClick,
    destoryVideo,
    reloadVideo
  };
};
export default useFlv;
